package com.ltcode.listener;

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.model.ModelProvider;
import dev.langchain4j.model.chat.listener.ChatModelErrorContext;
import dev.langchain4j.model.chat.listener.ChatModelListener;
import dev.langchain4j.model.chat.listener.ChatModelRequestContext;
import dev.langchain4j.model.chat.listener.ChatModelResponseContext;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.ToolChoice;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.output.TokenUsage;

import java.util.List;

/**
 * @Author： ltcode
 * @Create by： 2025/8/11 0011 20:41
 * @ClassName: ChatModelListener
 * @Describe：自定义监听chatModel 请求和响应
 */

public class ChatModeCustomerListener implements ChatModelListener {
    public void onRequest(ChatModelRequestContext requestContext) {
        ModelProvider modelProvider = requestContext.modelProvider();
        System.out.println("modelProvider: " + modelProvider);
        ChatRequest chatRequest = requestContext.chatRequest();
        String modelName = chatRequest.modelName();
        System.out.println("modelName: " + modelName);
        ToolChoice toolChoice = chatRequest.toolChoice();
        System.out.println("toolChoice: " + toolChoice);
        List<ChatMessage> messages = chatRequest.messages();
        System.out.println("messages: " + messages);
    }

    public void onResponse(ChatModelResponseContext responseContext) {
        ChatResponse chatResponse = responseContext.chatResponse();
        AiMessage aiMessage = chatResponse.aiMessage();
        System.out.println("aiMessage: " + aiMessage);
        TokenUsage tokenUsage = chatResponse.tokenUsage();
        System.out.println("tokenUsage: " + tokenUsage);
    }

    public void onError(ChatModelErrorContext errorContext) {
        Throwable error = errorContext.error();
        System.out.println("error: " + error);
    }
}
